﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using FirstFloor.Documents.Controls;

namespace SampleBrowser.Behaviors
{
    /// <summary>
    /// Performs page rotation.
    /// </summary>
    public class LayoutRotateBehavior
        : Behavior<LayoutTransformer>
    {
        private PageContext page;
        private Button rotateButton;
        private double angle;

        /// <summary>
        /// Called after the behavior is attached to an AssociatedObject.
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.Loaded += OnLoaded;
            this.AssociatedObject.MouseEnter += OnMouseEnter;
            this.AssociatedObject.MouseLeave += OnMouseLeave;
        }

        /// <summary>
        /// Called when the behavior is being detached from its AssociatedObject, but before it has actually occurred.
        /// </summary>
        /// <remarks>Override this to unhook functionality from the AssociatedObject.</remarks>
        protected override void OnDetaching()
        {
            base.OnDetaching();

            this.AssociatedObject.Loaded -= OnLoaded;
            this.AssociatedObject.MouseEnter += OnMouseEnter;
            this.AssociatedObject.MouseLeave += OnMouseLeave;

            if (this.rotateButton != null) {
                this.rotateButton.Click -= OnRotateClick;
            }
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            // the current page details are available on the data context
            this.page = this.AssociatedObject.DataContext as PageContext;

            // find the rotate button
            this.rotateButton = (Button)this.AssociatedObject.FindName("Rotate");
            if (this.rotateButton != null) {
                this.rotateButton.Click += OnRotateClick;
            }
        }

        private void OnRotateClick(object sender, RoutedEventArgs e)
        {
            this.angle += 90;
            if (this.angle % 360 == 0) {
                this.angle = 0;
            }
            this.AssociatedObject.LayoutTransform = new RotateTransform { Angle = this.angle };
        }

        private void OnMouseEnter(object sender, MouseEventArgs e)
        {
            if (this.rotateButton != null) {
                this.rotateButton.Visibility = Visibility.Visible;
            }
        }

        private void OnMouseLeave(object sender, MouseEventArgs e)
        {
            if (this.rotateButton != null) {
                this.rotateButton.Visibility = Visibility.Collapsed;
            }
        }
    }
}
